<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <p>我的订单</p>
    </header>

    <!-- 加载中提示 -->
    <div class="loading" v-if="loading">
      加载中...
    </div>

    <!-- 订单列表部分 -->
    <template v-else>
      <!-- 如果没有订单数据，显示提示信息 -->
      <div v-if="orderArr.length === 0" class="empty-orders">
        暂无订单信息
      </div>
      
      <!-- 有订单数据时显示列表 -->
      <template v-else>
        <h3>未支付订单信息：</h3>
        <ul class="order">
          <li v-for="item in unpaidOrders" :key="item.orderId">
            <div class="order-info">
              <p>
                {{item.business.businessName}}
                <i class="fa fa-caret-down" @click="detailetShow(item)"></i>
              </p>
              <div class="order-info-right">
                <p class="total-price">&#165;{{item.orderTotal.toFixed(2)}}</p>
                <div class="order-info-right-icon" @click="goToPayment(item)">去支付</div>
              </div>
            </div>
            <ul class="order-detailet" v-show="item.isShowDetailet">
              <li v-for="odItem in item.list" :key="odItem.odId">
                <div class="food-info">
                  <span class="food-name">{{odItem.food?.foodName || '未知商品'}}</span>
                  <span class="food-quantity">x {{odItem.quantity}}</span>
                </div>
                <p class="food-price">&#165;{{((odItem.food?.foodPrice || 0) * odItem.quantity).toFixed(2)}}</p>
              </li>
              <li class="delivery-fee">
                <p>配送费</p>
                <p>&#165;{{item.business.deliveryPrice.toFixed(2)}}</p>
              </li>
            </ul>
          </li>
        </ul>

        <h3>已支付订单信息：</h3>
        <ul class="order">
          <li v-for="item in paidOrders" :key="item.orderId">
            <div class="order-info">
              <p>
                {{item.business.businessName}}
                <i class="fa fa-caret-down" @click="detailetShow(item)"></i>
              </p>
              <div class="order-info-right">
                <p class="total-price">&#165;{{item.orderTotal.toFixed(2)}}</p>
              </div>
            </div>
            <ul class="order-detailet" v-show="item.isShowDetailet">
              <li v-for="odItem in item.list" :key="odItem.odId">
                <div class="food-info">
                  <span class="food-name">{{odItem.food?.foodName || '未知商品'}}</span>
                  <span class="food-quantity">x {{odItem.quantity}}</span>
                </div>
                <p class="food-price">&#165;{{((odItem.food?.foodPrice || 0) * odItem.quantity).toFixed(2)}}</p>
              </li>
              <li class="delivery-fee">
                <p>配送费</p>
                <p>&#165;{{item.business.deliveryPrice.toFixed(2)}}</p>
              </li>
            </ul>
          </li>
        </ul>
      </template>
    </template>

    <!-- 底部菜单部分 -->
    <Footer></Footer>
  </div>
</template>

<script>
import Footer from '@/views/Footer.vue';
import { orderApi } from '@/api/order';
import { businessApi } from '@/api/business';

export default {
  name: 'OrderList',
  data() {
    return {
      orderArr: [],
      user: null,
      loading: false
    }
  },
  created() {
    this.user = this.$getSessionStorage('user');
    if (!this.user) {
      this.$router.push('/login');
      return;
    }
    this.loadOrders();
  },
  computed: {
    // 未支付订单
    unpaidOrders() {
      return this.orderArr.filter(item => 
        item.orderState === 0 && item.business
      );
    },
    // 已支付订单
    paidOrders() {
      return this.orderArr.filter(item => 
        item.orderState === 1 && item.business
      );
    }
  },
  methods: {
    async loadOrders() {
      this.loading = true;
      try {
        // 1. 获取订单基本信息
        const response = await orderApi.listOrdersByUserId({
          userName: this.user.userName
        });
        console.log('获取到的订单列表:', response);

        if (!response || !response.success) {
          throw new Error(response?.message || '获取订单列表失败');
        }

        let orders = response.data || [];

        // 2. 为每个订单获取详细信息
        const ordersWithDetails = await Promise.all(
          orders.map(async (order) => {
            try {
              // 获取订单明细
              const detailResponse = await orderApi.getOrderDetailetByOrderId(order.orderId);
              console.log(`订单 ${order.orderId} 的明细:`, detailResponse);

              if (!detailResponse || !detailResponse.success) {
                throw new Error('获取订单明细失败');
              }

              // 获取商家信息
              const businessResponse = await businessApi.getBusinessById(parseInt(order.businessId));
              console.log(`商家 ${order.businessId} 的信息:`, businessResponse);

              if (!businessResponse) {
                throw new Error('获取商家信息失败');
              }

              // 获取每个商品的详细信息
              const orderItems = await Promise.all(
                detailResponse.data.map(async (item) => {
                  try {
                    // 调用 getFoodById 获取食品详细信息
                    const foodResponse = await businessApi.getFoodById(item.foodId);
                    console.log(`食品 ${item.foodId} 的信息:`, foodResponse);
                    return {
                      ...item,
                      food: foodResponse || {
                        foodName: '未知商品',
                        foodPrice: 0
                      }
                    };
                  } catch (error) {
                    console.error(`获取食品 ${item.foodId} 信息失败:`, error);
                    return {
                      ...item,
                      food: {
                        foodName: '未知商品',
                        foodPrice: 0
                      }
                    };
                  }
                })
              );

              return {
                ...order,
                isShowDetailet: false,
                business: businessResponse,
                list: orderItems
              };
            } catch (error) {
              console.error(`获取订单 ${order.orderId} 的详情失败:`, error);
              return null;
            }
          })
        );

        // 过滤掉加载失败的订单
        this.orderArr = ordersWithDetails.filter(order => order && order.business);
        console.log('最终处理后的订单数组:', this.orderArr);
      } catch (error) {
        console.error('加载订单失败:', error);
        this.$message.error(error.message || '加载订单失败，请稍后重试');
      } finally {
        this.loading = false;
      }
    },
    detailetShow(orders) {
      orders.isShowDetailet = !orders.isShowDetailet;
      // 可以添加动画效果
      const icon = event.target;
      if (icon.classList.contains('fa-caret-down')) {
        icon.classList.toggle('active');
      }
    },
    goToPayment(order) {
      console.log('跳转到支付页面的订单ID:', order.orderId)
      this.$router.push({
        path: '/payment',
        query: {
          orderId: order.orderId
        }
      })
    }
  },
  components: {
    Footer
  }
}
</script>

<style scoped>
/****************** 总容器 ******************/
.wrapper {
  width: 100%;
  height: 100%;
}
/****************** header部分 ******************/
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097FF;
  color: #fff;
  font-size: 4.8vw;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}
/****************** 历史订单列表部分 ******************/
.wrapper h3:first-of-type {
  margin-top: 12vw;  /* 第一个标题需要 margin-top */
}

.wrapper h3 {
  margin-top: 4vw;   /* 其他标题只需要较小的 margin-top */
  box-sizing: border-box;
  padding: 4vw;
  font-size: 4vw;
  font-weight: 300;
  color: #999;
}
.wrapper .order {
  width: 100%;
}
.wrapper .order li {
  width: 100%;
}
.wrapper .order li .order-info {
  box-sizing: border-box;
  padding: 2vw 4vw;
  font-size: 4vw;
  color: #666;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.wrapper .order li .order-info .order-info-right {
  display: flex;
}
.wrapper .order li .order-info .order-info-right .order-info-right-icon {
  background-color: #f90;
  color: #fff;
  border-radius: 3px;
  margin-left: 2vw;
  user-select: none;
  cursor: pointer;
}
.wrapper .order li .order-detailet {
  width: 100%;
  background-color: #f8f8f8;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
}
.wrapper .order li .order-detailet li {
  width: 100%;
  box-sizing: border-box;
  padding: 2vw 4vw;
  color: #666;
  font-size: 3.2vw;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
}
.empty-orders {
  text-align: center;
  padding: 20vw 0;
  color: #999;
  font-size: 4vw;
}
.loading {
  text-align: center;
  padding: 20vw 0;
  color: #666;
  font-size: 4vw;
}
.wrapper .order li .order-info i {
  margin-left: 2vw;
  cursor: pointer;
  transition: transform 0.3s;
}

.wrapper .order li .order-info i.active {
  transform: rotate(180deg);
}

.wrapper .order li .order-info .order-info-right-icon {
  padding: 1vw 2vw;
  background-color: #f90;
  color: #fff;
  border-radius: 3px;
  margin-left: 2vw;
  user-select: none;
  cursor: pointer;
  font-size: 3.2vw;
}
</style>
